package edu.unc.comp410.colemangeer.data;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import static java.lang.System.out;
import org.apache.log4j.Logger;


public class ZipGatewayEmulator implements IZipGateway {

	// CONSTANTS
	private static int ROWLENGTH = 3;
	private static String INPUT_FILE_LOCATION = "resources/";
	private static String INPUT_FILE_NAME = "ZipDB.in";

	private static Logger log = Logger.getLogger(CustomerGatewayEmulator.class);
	
	// Data members
	Map<String, Zip> zipTable = new HashMap<String, Zip>();

	public ZipGatewayEmulator() 
	throws FileNotFoundException {
		log.info(this.toString());
		out.println( "load from file");
		loadFromFile(INPUT_FILE_LOCATION + INPUT_FILE_NAME);
	}
	
	public void clear() {
		zipTable.clear();
	}

	/**
	 * @return number of DB rows affected
	 */
	public int deleteById(int custId) {
		if (null == zipTable.remove(custId))
			return 0;
		else
			return 1;
	}

	public Zip getById(Integer searchId) {
		return zipTable.get(searchId);
	}
	
	public Zip getByZipCode(String theZipCode) {
		return zipTable.get(theZipCode);
	}
	
	public Integer getNextUnusedId() {
		return 666;
	}

	public void insert(Zip theZip) {
		zipTable.remove(theZip);
		store(theZip);
	}
	
	public void loadFromFile( String inputFile )
	throws FileNotFoundException {
		Scanner inp = new Scanner( new File( inputFile ) );
		while( inp.hasNext() ) {
			String line = inp.nextLine();
//			out.println(line);
			Zip z = Zip.string2Object(line);
			zipTable.put( z.getZipCode(), z );		
		}
	}

	public int size() {
		return zipTable.size();
	}

	/**
	 * @return number of DB rows affected
	 */
	public void store(Zip theZip) {
		zipTable.put(theZip.getZipCode(), theZip);
	}


	public boolean successfulDBconnection() {
		return true;
	}

	@Override
	public String toString() {
		return "*** ZipGatewayEmulator";
	}
	
}
